﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace Windy.Transformations
{
    public static class TransformationExtension
    {
        public static void ApplyToList<TKey, TItem>(this Transformation<TKey, TItem, TItem> transformation, IList<TItem> list)
        {
            Contract.Requires(transformation != null, "ruleSet is null.");
            Contract.Requires(list != null, "list is null.");

            using (var sink = new ReversedCachedTransformSink<TItem, TItem>())
            {
                sink
                .SetupVoidTransformSink((index, item) => list.RemoveAt(index))
                .SetupMonoTransformSink((index, item, output) => { list[index] = output; })
                .SetupVaryTransformSink((index, item, output, addAction) =>
                    {
                        foreach (var foOutput in output.AsIndexedEnumerable(index))
                        {
                            var i = index;
                            var v = foOutput.Item;
                            addAction(() => list.Insert(i, v));
                        }
                        addAction(() => list.RemoveAt(index));
                    });

                transformation.ApplyTo(list, sink);
            }
        }
    }
}
